const { pool } = require('../config/db');

class Assessment {
  // 创建新测评
  static async create(assessmentData) {
    const { title, description, duration } = assessmentData;
    const query = 'INSERT INTO assessments (title, description, duration) VALUES (?, ?, ?)';
    const [result] = await pool.execute(query, [title, description, duration]);
    return result.insertId;
  }

  // 获取所有测评
  static async getAll() {
    const query = 'SELECT * FROM assessments ORDER BY created_at DESC';
    const [rows] = await pool.execute(query);
    return rows;
  }

  // 根据ID获取测评
  static async getById(id) {
    const query = 'SELECT * FROM assessments WHERE id = ?';
    const [rows] = await pool.execute(query, [id]);
    return rows[0];
  }

  // 更新测评
  static async update(id, assessmentData) {
    const { title, description, duration } = assessmentData;
    const query = 'UPDATE assessments SET title = ?, description = ?, duration = ? WHERE id = ?';
    await pool.execute(query, [title, description, duration, id]);
  }

  // 删除测评
  static async delete(id) {
    const query = 'DELETE FROM assessments WHERE id = ?';
    await pool.execute(query, [id]);
  }

  // 搜索测评
  static async search(queryStr) {
    const query = 'SELECT * FROM assessments WHERE title LIKE ? OR description LIKE ?';
    const [rows] = await pool.execute(query, [`%${queryStr}%`, `%${queryStr}%`]);
    return rows;
  }
}

module.exports = Assessment;